from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QStackedWidget, QLabel, QMessageBox
from PySide6.QtGui import QIcon
from theme.ui import ThemePanel
from logger.ui import LoggerPanel
from terminal.settings import TerminalPanel
import os

class SettingsPanel(QWidget):
    def __init__(self, theme_manager, log_manager, parent=None):
        super().__init__(parent)
        self.theme_manager = theme_manager
        self.log_manager = log_manager
        self.init_ui()
        
    def init_ui(self):
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 创建左侧导航栏
        nav_container = QWidget()
        nav_container.setFixedWidth(200)
        nav_layout = QVBoxLayout(nav_container)
        nav_layout.setContentsMargins(16, 16, 16, 16)
        nav_layout.setSpacing(8)
        
        # 添加导航按钮
        self.theme_btn = self.create_nav_button("主题设置")
        self.terminal_btn = self.create_nav_button("终端设置")
        self.logger_btn = self.create_nav_button("日志设置")
        
        self.theme_btn.setProperty("selected", True)
        self.terminal_btn.setProperty("selected", False)
        self.logger_btn.setProperty("selected", False)
        
        nav_layout.addWidget(self.theme_btn)
        nav_layout.addWidget(self.terminal_btn)
        nav_layout.addWidget(self.logger_btn)
        nav_layout.addStretch()
        
        # 创建右侧内容区
        content_container = QWidget()
        content_layout = QVBoxLayout(content_container)
        content_layout.setContentsMargins(24, 24, 24, 24)
        content_layout.setSpacing(16)
        
        # 创建堆叠部件用于切换内容
        self.stack_widget = QStackedWidget()
        
        # 添加主题设置页面
        self.theme_panel = ThemePanel(self.theme_manager)
        self.stack_widget.addWidget(self.theme_panel)
        
        # 添加终端设置页面
        self.terminal_panel = TerminalPanel()
        self.stack_widget.addWidget(self.terminal_panel)
        
        # 添加日志设置页面
        self.logger_panel = LoggerPanel(self.log_manager)
        self.stack_widget.addWidget(self.logger_panel)
        
        content_layout.addWidget(self.stack_widget)
        
        # 添加底部按钮栏
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 16, 0, 0)
        button_layout.setSpacing(8)
        
        save_button = QPushButton("保存")
        save_button.setObjectName("primaryButton")
        save_button.clicked.connect(self.save_settings)
        
        button_layout.addStretch()
        button_layout.addWidget(save_button)
        
        content_layout.addLayout(button_layout)
        
        # 添加到主布局
        layout.addWidget(nav_container)
        layout.addWidget(content_container)
        
        # 连接导航按钮信号
        self.theme_btn.clicked.connect(lambda: self.switch_page(0, self.theme_btn, [self.terminal_btn, self.logger_btn]))
        self.terminal_btn.clicked.connect(lambda: self.switch_page(1, self.terminal_btn, [self.theme_btn, self.logger_btn]))
        self.logger_btn.clicked.connect(lambda: self.switch_page(2, self.logger_btn, [self.theme_btn, self.terminal_btn]))
        
    def create_nav_button(self, text):
        button = QPushButton(text)
        button.setObjectName("settings_nav_button")
        button.setCheckable(True)
        return button
        
    def switch_page(self, index, clicked_btn, other_btns):
        self.stack_widget.setCurrentIndex(index)
        clicked_btn.setProperty("selected", True)
        for btn in other_btns:
            btn.setProperty("selected", False)
        
        # 强制更新按钮样式
        for btn in [clicked_btn] + other_btns:
            btn.style().unpolish(btn)
            btn.style().polish(btn)
            
    def save_settings(self):
        try:
            # 保存主题设置
            current_theme = self.theme_panel.theme_manager.get_current_theme()
            main_window = self.window()
            if main_window and hasattr(main_window, 'apply_theme'):
                main_window.apply_theme(current_theme)
                
                # 更新导航按钮图标
                theme_type = "light" if "light" in current_theme.lower() else "dark"
                nav_buttons = main_window.nav_buttons
                button_icons = {
                    "终端": f"terminal-{theme_type}.png",
                    "模版": f"model-{theme_type}.png",
                    "版本": f"version-{theme_type}.png",
                    "设置": f"setting-{theme_type}.png"
                }
                
                for btn in nav_buttons:
                    if btn.toolTip() in button_icons:
                        icon_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'icons', button_icons[btn.toolTip()])
                        btn.setIcon(QIcon(icon_path))
                
                # 更新会话树形列表图标
                if hasattr(main_window, 'session_list'):
                    computer_icon = QIcon(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'icons', f'computer-{theme_type}.png'))
                    folder_icon = QIcon(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'icons', f'folder-{theme_type}.png'))
                    main_window.session_list.update_icons(computer_icon, folder_icon)
            
            # 保存终端设置
            self.terminal_panel.save_config()
            
            # 保存日志设置
            log_enabled = self.logger_panel.enable_logging.isChecked()
            log_dir = self.logger_panel.path_input.text()
            self.log_manager.set_logging_enabled(log_enabled)
            self.log_manager.set_log_dir(log_dir)
            
            # 记录保存成功的日志
            self.log_manager.write_log(
                self.log_manager.get_log_file_path('app'),
                "设置保存成功",
                "Settings"
            )
            
            # 显示保存成功提示
            QMessageBox.information(self, "保存成功", "设置已成功保存！")
            
        except Exception as e:
            # 记录保存失败的日志
            self.log_manager.write_log(
                self.log_manager.get_log_file_path('app'),
                f"设置保存失败: {str(e)}",
                "Settings"
            )
            
            # 显示保存失败提示
            QMessageBox.critical(self, "保存失败", f"设置保存失败：{str(e)}")